<!DOCTYPE html>
<html lang="zh-CN"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="model/boardModel">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>订单复检列表</title>

</head>
<body>

<div th:fragment="pagenav" th:remove="tag">
    <div th:replace="model/nav :: pageheader ('订单复检管理','复检管理')"></div>
</div>

<div th:fragment="content" th:remove="tag">


    <div class="row">
        <div class="col-xs-12">

            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">查询条件</h3>
                    <div class="box-tools pull-right">
                        <button class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
                    </div>
                </div>
                <!-- /.box-header -->
                <!-- form start -->
                <form role="form" id="queryForm" th:action="@{/order/recheckList}" method="post" >
                    <div class="box-body">
                        <div class="row">
                            <input type="hidden" th:name="status" value="500" />
                            <div class="col-xs-3">
                                <input type="text" th:name="orderNumSearch"  class="form-control input-sm" placeholder="订单号"/>
                            </div>
                            <div class="col-xs-3">
                                <select name="status" class="form-control select2" >
                                    <option value="500">待复检</option>
                                    <option value="600">已复检</option>
                                </select>
                            </div>
                            <div class="col-xs-3">
                                <button id="btn-query" type="button" class="btn btn-primary pull-right btn-sm">查询</button>
                            </div>
                        </div>
                    </div>
                    <!-- /.box-body -->

                    <div class="box-footer">

                    </div>
                </form>
            </div>


            <div class="box">

                <!-- /.box-header -->
                <div class="box-body">
                    <table id="dataTable" class="table table-striped table-bordered table-hover table-condensed">

                        <thead >
                        <tr>
                            <th>订单号</th>
                            <th>商品名称</th>
                            <th>所属门店</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                    </table>
                </div>
                <!-- /.box-body -->
            </div>
            <!-- /.box -->
        </div>
    </div>
    <form role="form" id="submitForm" class="form-horizontal"  method="post" >
        <div class="box-body" id="goodsforSubmit">

        </div>
    </form>
    <div class="modal fade" id="verifyModal" style="overflow:auto;overflow-y:scroll;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="width: 780px;">
            <div class="modal-content">
                <div class="modal-header" style="background-color: #307095;">
                    <button type="button" class="close" onclick="clearAllData();" data-dismiss="modal"  >
                        <span aria-hidden="true">&times;</span><span class="sr-only">关闭</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel2">物品质检</h4>
                </div>

                <div class="modal-body">
                    <div class="box-body" id="forqaMemo">
                        <table id="chioxTable" class="table table-condensed">
                            <tr>
                                <th>检查项</th>
                                <th>初检结果</th>
                                <th>复检结果</th>
                                <th>是否符合</th>
                                <th>上传图片</th>
                            </tr>
                        </table>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="submit" id="btn-verify" onclick="verify();" class="btn btn-primary">确认</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="detailModal" tabindex="-1" style="overflow:auto;overflow-y:scroll;" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header" style="background-color: #307095;">
                    <button type="button" class="close" data-dismiss="modal"  >
                        <span aria-hidden="true">&times;</span><span class="sr-only">关闭</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel2">质检详情</h4>
                </div>

                <div class="modal-body">
                    <div class="box-body">
                        <table id="detailTable" class="table table-condensed">
                            <tr>
                                <th>检查项</th>
                                <th>初检结果</th>
                                <th>复检结果</th>
                                <th>是否符合</th>
                                <th>查看图片</th>
                            </tr>
                        </table>
                    </div>

                </div>
                <div class="modal-footer">
                    <button type="submit" id="btn-detail"  class="btn btn-primary">确认</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <form action="/sysUpload/uploadImg" method="post" enctype="multipart/form-data">
            <input type="file" id="imageFile" name="file" />
        </form>
    </div>
    <!--图片信息 -->
    <div class="modal fade" id="pictureModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
                <img src="" style="width: 560px;height: 320px;"  id="imageUrl"/>
        </div>
    </div>
    <!-- DataTables -->
    <script th:src="@{/plugins/jQuery/jquery.ui.widget.js}"></script>
    <script th:src="@{/plugins/jQuery/jquery.fileupload.js}"></script>

    <script type="text/javascript">
        $(function (){
            var tables = $("#dataTable").dataTable({
                serverSide: true,//分页，取数据等等的都放到服务端去
                processing: true,//载入数据的时候是否显示“载入中”
                pageLength: 10,  //首次加载的数据条数
                ordering: false,//排序操作在服务端进行，所以可以关了。
                /*pagingType: "full_numbers",*/
                autoWidth: false,
                stateSave: true,//保持翻页状态，和tables.fnDraw(false);结合使用
                searching: false,
                ajax: {   //类似jquery的ajax参数，基本都可以用。
                    type: "post",//后台指定了方式，默认get，外加datatable默认构造的参数很长，有可能超过get的最大长度。
                    url: "/order/recheckList",
                    dataSrc: "data",//默认data，也可以写其他的，格式化table的时候取里面的数据
                    data: function (d) {//d是原始的发送给服务器的数据，默认很长。
                        var param = {}; //因为服务端排序，可以新建一个参数对象
                        param.draw = d.draw;
                        param.start = d.start;
                        param.length = d.length;
                        var formData = $("#queryForm").serializeArray();//把form里面的数据序列化成数组
                        formData.forEach(function (e) {
                            param[e.name] = e.value;
                        });
                        return param;//自定义需要传递的参数。
                    }
                },
                columns: [//对应上面thead里面的序列
                    {"data": 'orderNo'},
                    {"data": 'goodsName'}, //mData 表示发请求时候本列的列明，返回的数据中相同下标名字的数据会填充到这一列
                    {"data": 'storeName'},
                    {"data": 'status',defaultContent: "",
                        "render": function (data, type, full, callback) {
                            if(data==500)
                                return  /*<![CDATA[*/"<span class='label label-success'>待质检</span>"/*]]>*/;
                            else if(data>500)
                                return /*<![CDATA[*/"<span class='label label-danger'>质检完成</span>"/*]]>*/;
                        }
                    },
                    {"data": 'createTimeStr', defaultContent: ""},
                    {"data":'status',
                        "render": function (data, type, full, callback) {
                            /*<![CDATA[*/
                            if (data == 500)
                                return " <button id='delRow' class='btn btn-primary btn-sm' type='button'><i class='fa fa-hand-pointer-o'></i>去质检</button></div>";
                            else if (data >= 500)
                                return "<div class='btn-group'><button id='editRow' class='btn btn-primary btn-sm' type='button'><i class='fa fa-edit'></i>查看详情</button></div>";

                            /*]]>*/
                        }
                    }

                ],

                //每加载完一行的回调函数
                createdRow: function( row, data, index ) {
                    //修改单元格样式
                    //$('td', row).eq(5).css('font-weight',"bold").css("color","red");//获取到具体行具体格的元素
                },
                initComplete: function (setting, json) {
                    //初始化完成之后替换原先的搜索框。
                },

                language: {
                    lengthMenu: "",//不显示记录条数选择
                    //lengthMenu: '<select class="form-control input-xsmall">' + '<option value="5">5</option>' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>' + '<option value="40">40</option>' + '<option value="50">50</option>' + '</select>条记录',//左上角的分页大小显示。
                    processing: "加载中",//处理页面数据的时候的显示
                    /*<![CDATA[*/
                    paginate: {//分页的样式文本内容。
                        previous: "<",
                        next: ">",
                        first: "<<",
                        last: ">>"
                    },
                    /*]]>*/
                    zeroRecords: "没有数据",//table tbody内容为空时，tbody的内容。
                    //下面三者构成了总体的左下角的内容。
                    //info: "共 _PAGES_ 页，显示第 _START_ 到第 _END_ 条 ",//筛选之后得到 _TOTAL_ 条，初始 _MAX_ 条   左下角的信息显示，大写的词为关键字。
                    info: "共 _PAGES_ 页，显示第 _START_ 到第 _END_ 条",
                    infoEmpty: "0条记录",//筛选为空时左下角的显示。0条记录
                    infoFiltered: "",//筛选之后的左下角筛选提示(另一个是分页信息显示，在上面的info中已经设置，所以可以不显示)，
                    sSearch: "关键字："
                }

            });

            //查询按钮
            $("#btn-query").on("click", function () {
                tables.fnDraw();
            });
            $('#verifyModal').on('hide.bs.modal', function () {
                clearAllData();
            });
             $('#detailModal').on('hide.bs.modal', function () {
                $("#detailTable tr:gt(0)").remove();
            });
            $("#btn-detail").on("click", function () {
                $("#detailModal").modal("hide");
            });
            //查看详情
            $("#dataTable tbody").on("click", "#editRow", function () {
                var data = tables.api().row($(this).parents("tr")).data();
                $.ajax({
                    url: '/order/getCheckList',
                    type: 'POST',
                    data: {"goodsId": data.goodsId},
                    dataType: "json",
                    cache: "false",
                    success: function (result) {
                        if (result.success) {
                            /*<![CDATA[*/
                            $.each(result.goodsDetails,function(i,n){
                                var temp = "";
                                var showimg = "";
                                if(n.beforeCode == n.afterCode){
                                    temp = "<span class='label label-success'>符合</span>";
                                }else{
                                    temp = "<span class='label label-danger'>不符合</span>";
                                    showimg = "<button  type='button' style='width: 75px;height: 21px;font-size: 12px;text-align: center;padding-top: 2px;' class='btn btn-primary ' onclick='showPicture(\""+n.linkUrl+"\");'>点击查看</button>";
                                }
                                $("#detailTable").append("<tr><td>"+n.propName+"</td><td>"+n.beforeValue+"</td><td>"+n.afterValue+"</td><td>"+temp+"</td><td>"+showimg+"</td></tr>");
                                /*]]>*/
                            });

                        } else {
                            toastr.error(result.msg);
                        }
                    },
                    error: function (err) {
                        toastr.error("网络错误...");
                    }
                });
                $("#detailModal").modal("show");
            });
            //去质检
            $("#dataTable tbody").on("click", "#delRow", function () {
                var data = tables.api().row($(this).parents("tr")).data();
                $.ajax({
                    url: '/order/getCheckList',
                    type: 'POST',
                    data: {"goodsId": data.goodsId},
                    dataType: "json",
                    cache: "false",
                    success: function (result) {
                        /*<![CDATA[*/
                        if (result.success) {
                            $.each(result.goodsDetails,function(i,n){
                                var temp = "";
                                var choice = JSON.parse(result.productList);
                                $.each(choice,function (a,b) {
                                    if(b.code==n.propKey){
                                        $.each(b.choix,function (d,j) {
                                            if(n.beforeCode==j.code) {
                                                temp += "<option value='" + j.code + "' selPrice='" + j.price + "' selected='selected'>" + j.name + "</option>";
                                                $("#goodsforSubmit").append("<input type='hidden' name='details["+i+"].orderId' value='"+data.orderId+"'/><input type='hidden' name='details["+i+"].detailId' value='"+n.detailId+"'/><input type='hidden' name='details["+i+"].afterCode' value='"+j.code+"'/>" +
                                                    "<input type='hidden' name='details["+i+"].afterValue' value='"+j.name+"'/><input type='hidden' name='details["+i+"].afterPrice' value='"+j.price+"'/>");
                                            }else {
                                                temp += "<option value='" + j.code + "' selPrice='" + j.price + "'>" + j.name + "</option>";
                                            }
                                        })
                                    }
                                })
                                $("#chioxTable").append("<tr><td>"+n.propName+"</td><td>"+n.beforeValue+"</td><td><select onchange='checkThis(\""+data.orderId+"\",\""+n.beforeCode+"\","+i+",this);' datId='"+n.detailId+"'>"+temp+"</select></td><td><span class='label label-success'>符合</span></td><td></td></tr>");

                            });
                            $("#chioxTable").parent().append("<div class='form-group'><label  class='col-sm-2 control-label'>备注（选填）：</label> <div class='col-sm-9'><textarea class='form-control' placeholder='请输入备注信息...'></textarea> </div> </div>")
                            /*]]>*/
                        } else {
                            toastr.error(result.msg);
                        }
                    },
                    error: function (err) {
                        toastr.error("网络错误...");
                    }
                });

                $("#verifyModal").modal("show");
            })

            if($("#imageFile").prop("files")){
                $("#imageFile").fileupload({
                    autoUpload: true,//是否自动上传
                    url: "/sysUpload/uploadImg",//上传地址
                    dataType: 'json',
                    done: function (e,result) {//设置文件上传完毕事件的回调函数
                        if (result.result.result==200) {
                            alert(result.result.msg);
                            /*<![CDATA[*/
                            var linenum = $("#imageFile").attr("linenum");
                            var record = $("#imageFile").attr("record");
                            $("#goodsforSubmit").append("<input type='hidden' name='details[" + linenum + "].linkUrl' value='" + result.result.data + "'/>")
                            changeTable(linenum, result.result.data.toString());
                            /*]]>*/
                        }else{
                            alert(result.result.msg);
                        }
                    }
                });
            }
            $("#btn-verify").click(function () {
                /*<![CDATA[*/
                for (var i=1;i<$('#chioxTable tr').length;i++)
                {
                    if($("#chioxTable tr:eq("+i+")").find("button").text() == "点击上传"){
                        return toastr.error("请上传不符合项图片！");
                    }
                }
                if($('#chioxTable').find("span").length == $('#chioxTable  tr').length-1 ){
                    if($("#chioxTable").find(".label-danger").length>0) {
                        $("#goodsforSubmit").append("<input type='hidden' name='status' value='600'/><input type='hidden' name='checkStatus' value='false'/>")
                    }else{
                        $("#goodsforSubmit").append("<input type='hidden' name='status' value='600'/><input type='hidden' name='checkStatus' value='true'/>")
                    }
                    var qaMemo = $("#forqaMemo textarea").val();
                    $("#goodsforSubmit").append("<input type='hidden' name='qaMemo' value='"+qaMemo+"'/>");
                    $("#btn-verify").attr("disabled",true);
                    /*]]>*/
                    $.ajax({
                        url: '/order/saveRecheck',
                        type: 'POST',
                        data: $("#submitForm").serialize(),
                        dataType: "json",
                        cache: "false",
                        success: function (result) {
                            if (result.result == 200) {
                                $("#btn-verify").attr("disabled",false);
                                $("#verifyModal").modal("hide");
                                toastr.success(result.msg);
                                $("#goodsforSubmit > input").remove();
                                $("#chioxTable tr:gt(0)").remove();
                                $("#forqaMemo .form-group").remove();
                                i=0;
                                //window.location.reload();
                                tables.fnDraw();
                            } else {
                                $("#btn-verify").attr("disabled",false);
                                toastr.error(result.msg);
                            }
                        },
                        error: function (err) {
                            $("#btn-verify").attr("disabled",false);
                            toastr.error("网络错误...");
                        }
                    });


                }else{
                    return toastr.error("请检查每一条检查项！");
                }

            });

        })
        var i = 0;
        function checkThis(orderId,beforeCode,linenum,obj) {
            /*<![CDATA[*/
            var afterPrice = $(obj).find("option:selected").attr("selPrice");
            var afterValue = $(obj).find("option:selected").text();
            if(beforeCode == $(obj).val()){
                $(obj).parent().next().text("");
                $(obj).parent().next().append("<span class='label label-success'>符合</span>")
                $(obj).parent().next().next().find("input").remove();
                $(obj).parent().next().next().find("button").remove();
                $("#goodsforSubmit input[name='details\["+linenum+"\].linkUrl']").remove();
            }else{
                $(obj).parent().next().text("");
                $(obj).parent().next().append("<span class='label label-danger'>不符合</span>")
                $(obj).parent().next().next().find("input").remove();
                $(obj).parent().next().next().find("button").remove();
                $("#goodsforSubmit input[name='details\["+linenum+"\].linkUrl']").remove();
                $(obj).parent().next().next().append("<input type='hidden' name='recordno' linenum='"+linenum+"' value='"+i+"'/><button class='btn btn-success' style='width: 75px;height: 21px;font-size: 12px;text-align: center;padding-top: 2px;' onclick='uploadImage(this);'>点击上传</button>")
            }
            $("#goodsforSubmit input[name='details\["+linenum+"\].afterCode']").val($(obj).val());
            $("#goodsforSubmit input[name='details\["+linenum+"\].afterValue']").val(afterValue);
            $("#goodsforSubmit input[name='details\["+linenum+"\].afterPrice']").val(afterPrice);

            i++;
            /*]]>*/
        }
        /*function verify() {
            /!*<![CDATA[*!/
            for (var i=1;i<$('#chioxTable tr').length;i++)
            {
                if($("#chioxTable tr:eq("+i+")").find("button").text() == "点击上传"){
                    return toastr.error("请上传不符合项图片！");
                }
            }
            if($('#chioxTable').find("span").length == $('#chioxTable  tr').length-1 ){
                if($("#chioxTable").find(".label-danger").length>0) {
                    $("#goodsforSubmit").append("<input type='hidden' name='status' value='600'/><input type='hidden' name='checkStatus' value='false'/>")
                }else{
                    $("#goodsforSubmit").append("<input type='hidden' name='status' value='600'/><input type='hidden' name='checkStatus' value='true'/>")
                }
                var qaMemo = $("#forqaMemo textarea").val();
                $("#goodsforSubmit").append("<input type='hidden' name='qaMemo' value='"+qaMemo+"'/>");
                $("#btn-verify").attr("disabled",true);
                /!*]]>*!/
                    $.ajax({
                        url: '/order/saveRecheck',
                        type: 'POST',
                        data: $("#submitForm").serialize(),
                        dataType: "json",
                        cache: "false",
                        success: function (result) {
                            if (result.result == 200) {
                                $("#btn-verify").attr("disabled",false);
                                $("#verifyModal").modal("hide");
                                toastr.success(result.msg);
                                $("#goodsforSubmit > input").remove();
                                $("#chioxTable tr:gt(0)").remove();
                                $("#forqaMemo .form-group").remove();
                                i=0;
                                window.location.reload();
                            } else {
                                toastr.error(result.msg);
                            }
                        },
                        error: function (err) {
                            toastr.error("网络错误...");
                        }
                    });


            }else{
                return toastr.error("请检查每一条检查项！");
            }

        }*/
        function clearAllData() {
            $("#goodsforSubmit > input").remove();
            $("#chioxTable tr:gt(0)").remove();
            $("#forqaMemo .form-group").remove();
            i=0;
        }
        function uploadImage(obj) {
            //record第几条记录 linenum为行
            $(obj).attr("disabled",true);
            $("#imageFile").attr("record",$(obj).parent().find("input").val());
            $("#imageFile").attr("linenum",$(obj).parent().find("input").attr("linenum"));
            $("#imageFile").click();
        }
        function changeTable(lineno,imgsrc) {
            /*<![CDATA[*/
            var line = parseInt(lineno)+1;
            $("#chioxTable tr:eq("+line+")").find("button").remove();
            $("#chioxTable tr:eq("+line+") td:eq(4)").append("<button  type='button' style='width: 75px;height: 21px;font-size: 12px;text-align: center;padding-top: 2px;' class='btn btn-primary ' onclick='showPicture(\""+imgsrc+"\");'>查看图片</button>");
            /*]]>*/
        }
        function showPicture(imgsrc){
            $("#imageUrl").attr("src",imgsrc);
            $("#pictureModal").modal("show");
        }

    </script>


</div>
</body>
</html>